//
//  XQWebController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/4.
//

import UIKit
import WebKit

class XQWebController: XQBaseController,WKNavigationDelegate {
        
    var url : String = ""
    var webView: WKWebView!
    var progressView: UIProgressView!
    var webConfiguration : WKWebViewConfiguration!
    var js : XQJSHelper!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        setupNav()
        setupWebView()
        setJS()
        setupProgressView()
        loadRequest()
    }
    
    private func setupNav() {
        self.backIcon = "black_back"
    }
    
    private func setupWebView() {
        let configuration = WKWebViewConfiguration()
        let preferences = WKWebpagePreferences()
        preferences.allowsContentJavaScript = true
        configuration.defaultWebpagePreferences = preferences
        
        webConfiguration = configuration
                
        webView = WKWebView(frame: CGRect(x: 0, y: UIDevice.xq_topHeight(),
                                          width: UIScreen.main.bounds.width,
                                          height: UIScreen.main.bounds.height - UIDevice.xq_topHeight() - UIDevice.xq_bottomSafeMargin()),
                            configuration: configuration)
        
        webView.scrollView.backgroundColor = .white
        webView.navigationDelegate = self
        webView.allowsBackForwardNavigationGestures = true // 打开网页间的滑动返回
        webView.scrollView.decelerationRate = .normal
        
        // 监控进度
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)

        view.addSubview(webView)
    }
    
    private func setupProgressView() {
        progressView = UIProgressView(progressViewStyle: .default)
        progressView.tintColor = .mainTextColor
        progressView.trackTintColor = .clear
        progressView.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 3.0)
        webView.addSubview(progressView)
    }
    
    private func setJS() {
        js = XQJSHelper.init(viewController: self, configuration: self.webConfiguration)
    }
    
    private func loadRequest() {
        if let url = URL(string:url) { // 替换为您的 URL
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progressView.progress = Float(webView.estimatedProgress)
            if progressView.progress == 1 {
                UIView.animate(withDuration: 0.25, delay: 0.3, options: .curveEaseInOut, animations: {
                    self.progressView.transform = CGAffineTransform(scaleX: 1.0, y: 1.4)
                }) { finished in
                    self.progressView.isHidden = true
                }
            }
        } else if keyPath == "title" {
            if let title = webView.title {
                if title.count > 12 {
                    let truncatedTitle = String(title.prefix(12)) + "..."
                    self.navTitle = truncatedTitle
                } else {
                    self.navTitle = title
                }
            }
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        self.progressView.isHidden = true
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard let url = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }
        let scheme = url.scheme
        // 打电话
        if scheme == "tel" {
            let app = UIApplication.shared
            if app.canOpenURL(url) {
                openWebPage(url.absoluteString)
                decisionHandler(.cancel) // 取消导航
                return
            }
        }
        // 打开 App Store
        if url.absoluteString.contains("itunes.apple.com") {
            let app = UIApplication.shared
            if app.canOpenURL(url) {
                openWebPage(url.absoluteString)
                decisionHandler(.cancel) // 取消导航
                return
            }
        }
        // 如果是跳转到一个新页面
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request) // 加载新请求
            decisionHandler(.allow) // 允许导航
            return
        }
        decisionHandler(.allow) // 默认允许导航
    }

    // 处理导航响应
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    override func onBack() {
        if self.webView.canGoBack {
            self.webView.goBack()
        }else {
            super.onBack()
        }
    }
    
    private func openWebPage(_ urlString: String) {
        if let url = URL(string: urlString) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }


}
